//index.js
//获取应用实例
var app = getApp();

var Logger = app.modules['Logger'];
var Request = app.modules['Request'];
var Auth = app.modules['Auth'];

var Model = require('../../models/Model.js');
var MUser = require('../../models/MUser.js');

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onHide:function(){
    console.log("onHide");
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
      if(Auth.user()){
          this.setData({
              userInfo:Auth.user()
          });
      }
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  onTestClick:function(e){
    //   Request.get('/test-session.php').then(function (res) {

    //   });
    // Model.find(1);
    //   var model = Model.create('/user');
    //   model.id =1;
    //   model.name = '123';
    //   model.create();

        var User = MUser.init();

        //新增
        User
            .create({id:1,name:'zhangsan'})
            .then(User.update(1, { name: '456' }))
            .then(User.remove(1));

  },
  onLoginBtnClick:function(e){
      var self = this;
      wx.login({
          success: function (res) {
              //得到js_code
              var code = res.code;
              var loginInfo = {
                  code: code
              };
              Auth.attempt(loginInfo, function (auth_info) {
                  self.setData({
                      userInfo:auth_info.user
                  });
              }.bind(this));
          }
      });
      
  }
})
